#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 150010;
using PII = pair<int, int>;
int e[N], ne[N], h[N], w[N], idx = 0;
bool flag[N];
priority_queue<PII, vector<PII>, greater<PII>> q;
int dist[N];
void add(int a, int b, int c)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx, w[idx++] = c;
}
int n, m;

int djstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    q.push({ 0, 1 });
    while (q.size())
    {
        auto t = q.top();
        q.pop();
        int dst = t.first, num = t.second;
        if (num == n) return dst;
        if (flag[num]) continue;
        flag[num] = true;
        for (int i = h[num]; ~i; i = ne[i])
        {
            int j = e[i];
            if (!flag[j] && dst + w[i] < dist[j])
            {
                dist[j] = dst + w[i];
                q.push({ dist[j], j });
            }
        }
    }
    return -1;
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    for (int i = 0; i < m; ++i)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    cout << djstra() << endl;
    return 0;
}